package com.sptpc.learnspring.controller;

import com.sptpc.learnspring.controller.request.NewCategoryRequest;
import com.sptpc.learnspring.model.Category;
import com.sptpc.learnspring.service.CategoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @GetMapping(value = "/", params = "!name")
    public ModelAndView getAll(){
        ModelAndView mv = new ModelAndView("category/index");
        List<Category> categoryList = categoryService.findAll();
        mv.addObject("clist",categoryList);

        return mv;
    }

    // /category/
//    @GetMapping(value = "/", params = "!name")
//    public List<Category> getAll(){
//        return categoryService.findAll();
//    }

    // /category/?name='xxx'
//    @GetMapping(value = "/", params = "name")
//    public Category getCategory(@RequestParam String name){
//        return categoryService.findOne(name);
//    }

    // /category/10 restful path参数
//    @GetMapping(value = "/{id}")
//    public Category getCategory(@PathVariable Long id) {
//        return categoryService.findOne(id);
//    }

    // /category/save
//    @PostMapping("/save")
//    @ResponseStatus(code = HttpStatus.CREATED)
//    public Category saveCategory(Category category) {
//        return categoryService.saveCategory(category);
//    }

    // /category/save
    //http header request content-type accept
//    @PostMapping(value = "/save", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
//    @ResponseStatus(code = HttpStatus.CREATED)
//    public Category saveCategory(NewCategoryRequest categoryRequest){
//        Category category = new Category();
//        BeanUtils.copyProperties(categoryRequest, category);
//        return categoryService.saveCategory(category);
//    }

    // /category/save
//    @PostMapping(value = "/save", consumes = MediaType.APPLICATION_JSON_VALUE)
//    @ResponseStatus(code = HttpStatus.CREATED)
//    public Category saveCategoryWithJson(@RequestBody NewCategoryRequest categoryRequest){
//        Category category = new Category();
//        BeanUtils.copyProperties(categoryRequest, category);
//        return categoryService.saveCategory(category);
//    }

}
